package com.ihrm.atte.service;

import com.ihrm.atte.dao.AttendanceConfigDao;
import com.ihrm.atte.dao.AttendanceDao;
import com.ihrm.atte.dao.UserDao;
import com.ihrm.common.poi.ExcelImportUtil;
import com.ihrm.common.utils.DateUtil;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.domain.atte.entity.Attendance;
import com.ihrm.domain.atte.vo.AtteUploadVo;
import com.ihrm.domain.system.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


@Log4j2
@Service
public class ExcelImportService {
    
    @Autowired
    private UserDao userDao;
    
    @Autowired
    private AttendanceDao attendanceDao;
    
    @Autowired
    private AttendanceConfigDao attendanceConfigDao;
    
    @Autowired
    private IdWorker idWorker;
    
    @Value("${atte.holidays}")
    private String holidays;
    
    @Value("${atte.wordingDays}")
    private String wordingDays;
    
    /**
     * 处理考勤数据的文件上传
     */
    public void importAttendanceExcel(MultipartFile file,String companyId) throws Exception{
        /**
         * 将导入的Excel文件解析为vo的list集合
         */
        List<AtteUploadVo> list = new ExcelImportUtil<AtteUploadVo>(AtteUploadVo.class).readExcel(file.getInputStream(), 1, 0);
        
        /**
         * 循环list集合
         */
        for(AtteUploadVo atteUploadVo:list){
    
            /**
             * 根据用户上传的手机号查询用户
             */
            User user = userDao.findByMobile(atteUploadVo.getMobile());
    
            /**
             * 构造考勤对象
             */
            Attendance attendance = new Attendance(atteUploadVo, user);
            attendance.setDay(atteUploadVo.getAtteDate());
            
            /**
             * 判断是否休假
             */
            /**
             * 1.将国家的假日记录到数据库
             * 2.文件
             */
            if(holidays.contains(atteUploadVo.getAtteDate())){
                /**
                 * 休息
                 */
                attendance.setAdtStatu(23);
            }else if(DateUtil.isWeekend(atteUploadVo.getAtteDate())&&!wordingDays.contains(atteUploadVo.getAtteDate())){
                attendance.setAdtStatu(23);
            }else {
                /**
                 * 正常
                 */
                attendance.setAdtStatu(1);
            }
    
            /**
             * 查询用户是否已经有考勤记录，如果不存在，保存数据库
             */
            Attendance byUserIdAndDay = attendanceDao.findByUserIdAndDay(user.getId(), atteUploadVo.getAtteDate());
            
            if(byUserIdAndDay==null){
                attendance.setId(idWorker.nextId()+"");
                attendanceDao.save(attendance);
            }
        }
    }

}
